package malitech.framework.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * This class implements a simple token replacer ( Ant like)
 *  
 * @author ech
 * 
 */
public class TokenReplacer
{
    private Map<String, Object> map = new HashMap<String, Object>();

    /**
     * add a key and its value into the Token Replacer if key already exists, it's updated
     * 
     * @param key
     * @param value
     */
    public void add(String key, Object value)
    {
        if (value == null)
        {
            map.put(key, "");
        }
        else
        {
            map.put(key, value);
        }
    }

    /**
     * Remove the specified entry. if not found... do nothing
     * 
     * @param key
     */
    public void remove(String key)
    {
        map.remove(key);
    }

    /**
     * remove all entries where the key starts with the parameter
     * 
     * @param startOfKey
     */
    public void removeAllStartingWith(String startOfKey)
    {
        if (startOfKey == null)
        {
            return;
        }
        Set<String> keys = map.keySet();
        Iterator<String> i = keys.iterator();
        while (i.hasNext())
        {
            String s = i.next();
            if (s.startsWith(startOfKey))
            {
                i.remove();
            }
        }
    }

    /**
     * replace all instances of ${key} with the associated value. If the value is not a string then toString is used
     * 
     * @param inputString
     * @return
     */
    public String expand(String inputString)
    {
        String s = inputString;
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();
        for (Map.Entry<String, Object> entry : entrySet)
        {
            s = s.replace("${" + entry.getKey() + "}", entry.getValue().toString());
        }
        return s;
    }
}
